import Vue from 'vue';
import Axios from 'axios';
import copy from 'copy-to-clipboard';
import json = Mocha.reporters.json;


const md5 = require('md5');
const Qs = require('qs');

interface headerObject {
    version: string;
    token: any | null;
    type: string;
    noncestr: string;
    did: string;
    sign: string;
    'Content-Type': string;
}

export default class Sence extends Vue {
    // public apiurl: string = 'http://cyw.haitow.com/'; // 域名配置
    // public apiurl: string = 'http://xh.xmxhzx.cn/'; // 域名配置
    public apiurl: string = 'http://xh.xmxhzx.cn/'; // 域名配置
    // public localApiurl: string = 'http://hn.anyyun.cn/'; // 域名配置
    public pagesize: number = 6; // 页面记录数配置
    public loginType: string = 'h5'; //登录环境
    constructor() {
        super();
        if (process.env.NODE_ENV === 'development') {
            this.apiurl = '/site';
        }
    }

    public api: any = {
        key: 'CYW2019ANYIDC',
    }; // 系统配置参数


    public apihead: headerObject = {
        version: '1.1',
        token: '',
        type: 'wap',
        noncestr: '',
        did: '',
        sign: '',
        'Content-Type': 'text/html; charset=utf-8',
    }; // 接口头配置参数

    public apiheader(): object {  // 接口头数据处理
        this.apihead.token = localStorage.getItem('token') || '';
        this.apihead.noncestr = md5(Date.parse(new Date().toString()).toString());
        this.apihead.did = Date.parse(new Date().toString()).toString();
        this.apihead.sign = md5(md5('did=' + this.apihead.did + '&noncestr=' + this.apihead.noncestr + '&token=' + this.apihead.token + '&type=' + this.apihead.type + '&version=' + this.apihead.version) + this.api.key);
        return this.apihead;
    }

    public get(url: string, obj: any = {}): any {
        let promise: object = new Promise((resolve, reject) => {
            Axios.get(this.apiurl + url, {headers: this.apiheader(), params: obj}).then(res => {
                resolve(res.data);
            })
                .catch(err => {
                    reject(err);
                });
        });
        return promise;
    }

    public post(url: string, obj: any = {}): any {
        this.isWeiXin();
        let promise: object = new Promise((resolve, reject) => {
            Axios.post(this.apiurl + 'index.php?s=/' + url, {
                ...obj,
                wxapp_id: 10001,
                token: localStorage.getItem('token') || '',
                login_type: this.loginType
            })
                .then(res => {
                    if (res.data.code == 1) {
                        resolve(res.data);
                    } else if (res.data.code == -1) {
                        localStorage.removeItem('token');
                        localStorage.removeItem('third_id');
                        this.getCode();
                        reject(res);
                        // this.$router.push('/registe');
                    } else {
                        (<any> this).$createDialog({
                            type: 'alert',
                            title: '提示',
                            content: res.data.msg,
                            icon: 'cubeic-alert',
                        }).show();
                        reject(res);
                        // this.toast(res.data.message,'warn');
                    }
                })
                .catch(err => {
                    reject(err);
                });
        });
        return promise;
    }

    public GetRequest(url: string): any {
        var theRequest: any = {};
        if (url.indexOf('?') != -1) {
            var str: any = url.substring(url.indexOf('?') + 1);
            // console.log(str);
            let strs: any = str.split('&');
            // console.log(strs);
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1]);
            }
        }
        return theRequest;
    }

    // 信息弹出框
    public toast(txt: string, type: string = 'correct'): void {
        const toast = (<any> this).$createToast({
            txt,
            type,
        });
        toast.show();
    }

    // 存缓存
    public set(key: string, data: any): void {
        localStorage.setItem(key, JSON.stringify(data));
    }

    // // 取用户缓存
    // public getuser(): any {
    //     let user: any = localStorage.getItem('user');
    //     return JSON.parse(user);
    // }

    // 更新用户信息
    public freshUser(): any {
        let promise: object = new Promise((resolve, reject) => {
            this.post('api/user/detail').then((res: any) => {
                // this.set('user', res.data.userInfo);
                resolve(res.data.userInfo);
            });
        });
        return promise;
    }

    // 复制
    public copy(data: string): void {
        copy(data);
    }


    // 显示加载
    public showLoading(): void {
        (<any> this).$createToast({
            txt: 'Loading...',
            mask: true,
            time: 10000,
        }).show();
    }


    // 隐藏加载
    public hideLoading(): void {
        (<any> this).$createToast({}).hide();
    }

    /**
     * 判断是否微信端打开
     */
    public isWeiXin(): any {
        let ua: any = window.navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
            this.loginType = 'wechat'; //在微信内打开
        } else {
            this.loginType = 'h5';
        }
    }

    /**
     * 微信请求code接口
     */
    public getCode():any{
        location.href=this.apiurl + 'index.php?s=/api/wechat/getCode&wxapp_id=10001&url='+this.apiurl+'dist/#/';
    }


}
